"""
QoPilot 日志配置模块
提供统一的日志配置和管理
"""

import logging
import logging.handlers
from pathlib import Path


class QoPilotLogger:
    """QoPilot 日志管理器"""

    def __init__(self, name: str = "qopilot"):
        self.name = name
        self.logger = logging.getLogger(name)
        self._setup_logger()

    def _setup_logger(self):
        """设置日志配置"""
        # 避免重复配置
        if self.logger.handlers:
            return

        # 设置日志级别
        self.logger.setLevel(logging.INFO)

        # 创建日志目录
        log_dir = Path("logs")
        log_dir.mkdir(exist_ok=True)

        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_formatter = logging.Formatter(
            '%(asctime)s | %(name)s | %(levelname)s | %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        console_handler.setFormatter(console_formatter)

        # 文件处理器 - 按日期轮转
        file_handler = logging.handlers.TimedRotatingFileHandler(
            filename=log_dir / "qopilot.log",
            when='midnight',
            interval=1,
            backupCount=30,
            encoding='utf-8'
        )
        file_handler.setLevel(logging.DEBUG)
        file_formatter = logging.Formatter(
            '%(asctime)s | %(name)s | %(levelname)s | %(filename)s:%(lineno)d | %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        file_handler.setFormatter(file_formatter)

        # 错误日志文件处理器
        error_handler = logging.handlers.TimedRotatingFileHandler(
            filename=log_dir / "qopilot_error.log",
            when='midnight',
            interval=1,
            backupCount=30,
            encoding='utf-8'
        )
        error_handler.setLevel(logging.ERROR)
        error_handler.setFormatter(file_formatter)

        # 添加处理器
        self.logger.addHandler(console_handler)
        self.logger.addHandler(file_handler)
        self.logger.addHandler(error_handler)

        # 防止日志重复
        self.logger.propagate = False

    def get_logger(self, name: str = None):
        """获取日志器"""
        if name:
            return logging.getLogger(f"{self.name}.{name}")
        return self.logger


# 全局日志管理器实例
qopilot_logger = QoPilotLogger()


# 便捷函数
def get_logger(name: str = None):
    """获取日志器的便捷函数"""
    return qopilot_logger.get_logger(name)


# 交易专用日志器
trading_logger = get_logger("trading")
data_logger = get_logger("data")
strategy_logger = get_logger("strategy")
backtest_logger = get_logger("backtest")
